package com.atguigu.lease.web.app.service.impl;

import com.atguigu.lease.common.interceptor.AuthenticationInterceptor;
import com.atguigu.lease.common.utils.JwtUtil;
import com.atguigu.lease.model.entity.*;
import com.atguigu.lease.model.enums.ItemType;
import com.atguigu.lease.model.enums.LeaseSourceType;
import com.atguigu.lease.model.enums.LeaseStatus;
import com.atguigu.lease.web.app.mapper.*;
import com.atguigu.lease.web.app.service.GraphInfoService;
import com.atguigu.lease.web.app.service.GraphService;
import com.atguigu.lease.web.app.service.LeaseAgreementService;
import com.atguigu.lease.web.app.vo.agreement.AgreementDetailVo;
import com.atguigu.lease.web.app.vo.agreement.AgreementItemVo;
import com.atguigu.lease.web.app.vo.graph.GraphVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestHeader;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author liubo
 * @description 针对表【lease_agreement(租约信息表)】的数据库操作Service实现
 * @createDate 2023-07-26 11:12:39
 */
@Service
public class LeaseAgreementServiceImpl extends ServiceImpl<LeaseAgreementMapper, LeaseAgreement> implements LeaseAgreementService {
    @Autowired
    private ApartmentInfoMapper apartmentMapper;

    @Autowired
    private RoomInfoMapper roomMapper;

    @Autowired
    private LeaseTermMapper leaseTermMapper;

    @Autowired
    private PaymentTypeMapper paymentTypeMapper;

    @Autowired
    private GraphService graphService;

    /**
     * 获取当前用户的租约列表基本信息
     * 实现思路:
     * 1. 通过当前登录用户的手机号获取该用户的所有租约信息
     * 2. 对于每个租约，查询关联的公寓、房间信息
     * 3. 获取房间图片，并判断租约是否可续约（只有已签约状态的租约才可续约）
     * 4. 封装成AgreementItemVo返回
     */
    @Override
    public List<AgreementItemVo> getAgreementItemListByCurrentUser(@RequestHeader("access_token") String token) {
        //从token获取手机号
        String phone = JwtUtil.parseToken(token).get("username",String.class);
        //String phone = "13185863695";

        // 查询该用户的所有未删除租约
        LambdaQueryWrapper<LeaseAgreement> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LeaseAgreement::getPhone, phone)
                .eq(LeaseAgreement::getIsDeleted, 0)
                .orderByDesc(LeaseAgreement::getCreateTime);

        List<LeaseAgreement> leaseAgreementList = baseMapper.selectList(queryWrapper);
        List<AgreementItemVo> result = new ArrayList<>();

        for (LeaseAgreement leaseAgreement : leaseAgreementList) {
            AgreementItemVo itemVo = new AgreementItemVo();
            // 复制基本属性
            BeanUtils.copyProperties(leaseAgreement, itemVo);

            // 查询公寓信息
            ApartmentInfo apartment = apartmentMapper.selectById(leaseAgreement.getApartmentId());
            if (apartment != null) {
                itemVo.setApartmentName(apartment.getName());
            }

            // 查询房间信息
            RoomInfo room = roomMapper.selectById(leaseAgreement.getRoomId());
            if (room != null) {
                itemVo.setRoomNumber(room.getRoomNumber());

                // 获取房间图片
                List<GraphVo> roomGraphVoList = graphService.getGraphVoListByRelatedId(leaseAgreement.getRoomId(), 2); // 假设2表示房间图片
                itemVo.setRoomGraphVoList(roomGraphVoList);
            }

            // 判断是否可续约（一般只有已签约状态的租约才可续约）
            itemVo.setIsRenewable(LeaseStatus.SIGNED.equals(leaseAgreement.getStatus()));

            result.add(itemVo);
        }

        return result;
    }

    /**
     * 根据ID获取租约详细信息
     * 实现思路:
     * 1. 根据租约ID查询租约基本信息
     * 2. 查询关联的公寓、房间、租期、支付方式等信息
     * 3. 获取公寓和房间的图片
     * 4. 封装成AgreementDetailVo返回
     */
    @Override
    public AgreementDetailVo getAgreementDetailById(Long id) {
        // 查询租约信息
        LeaseAgreement leaseAgreement = baseMapper.selectById(id);
        if (leaseAgreement == null || leaseAgreement.getIsDeleted() == 1) {
            return null;
        }

        AgreementDetailVo detailVo = new AgreementDetailVo();
        BeanUtils.copyProperties(leaseAgreement, detailVo);

        // 查询公寓信息
        ApartmentInfo apartment = apartmentMapper.selectById(leaseAgreement.getApartmentId());
        if (apartment != null) {
            detailVo.setApartmentName(apartment.getName());
            // 获取公寓图片
            List<GraphVo> apartmentGraphVoList = graphService.getGraphVoListByRelatedId(apartment.getId(), 1); // 假设1表示公寓图片
            detailVo.setApartmentGraphVoList(apartmentGraphVoList);
        }

        // 查询房间信息
        RoomInfo room = roomMapper.selectById(leaseAgreement.getRoomId());
        if (room != null) {
            detailVo.setRoomNumber(room.getRoomNumber());
            // 获取房间图片
            List<GraphVo> roomGraphVoList = graphService.getGraphVoListByRelatedId(room.getId(), 2); // 假设2表示房间图片
            detailVo.setRoomGraphVoList(roomGraphVoList);
        }

        // 查询租期信息
        LeaseTerm leaseTerm = leaseTermMapper.selectById(leaseAgreement.getLeaseTermId());
        if (leaseTerm != null) {
            detailVo.setLeaseTermMonthCount(leaseTerm.getMonthCount());
            detailVo.setLeaseTermUnit(leaseTerm.getUnit());
        }

        // 查询支付方式
        PaymentType paymentType = paymentTypeMapper.selectById(leaseAgreement.getPaymentTypeId());
        if (paymentType != null) {
            detailVo.setPaymentTypeName(paymentType.getName());
        }

        return detailVo;
    }

    /**
     * 更新租约状态
     * 实现思路:
     * 1. 根据ID查询租约
     * 2. 验证操作是否合法（比如不能将已取消的租约改为已签约）
     * 3. 更新租约状态
     */
    @Override
    public boolean updateAgreementStatus(Long id, LeaseStatus leaseStatus) {
        // 查询当前租约
        LeaseAgreement leaseAgreement = baseMapper.selectById(id);
        if (leaseAgreement == null || leaseAgreement.getIsDeleted() == 1) {
            return false;
        }

        // 这里可以添加状态转换的合法性验证
        // 例如：已取消的租约不能改为已签约，已退租的不能改为签约待确认等

        // 简单起见，这里直接更新状态
        leaseAgreement.setStatus(leaseStatus);
        leaseAgreement.setUpdateTime(new Date());

        return baseMapper.updateById(leaseAgreement) > 0;
    }

    /**
     * 保存或更新租约信息
     * 实现思路:
     * 1. 判断是新增还是更新
     * 2. 对于续约，设置来源类型为续约
     * 3. 保存或更新租约信息
     */
    @Override
    public boolean saveOrUpdateAgreement(LeaseAgreement leaseAgreement) {
        // 设置更新时间
        leaseAgreement.setUpdateTime(new Date());

        if (leaseAgreement.getId() == null) {
            // 新增租约
            leaseAgreement.setCreateTime(new Date());
            // 如果是续约，设置来源类型
            if (LeaseSourceType.RENEW.equals(leaseAgreement.getSourceType())) {
                leaseAgreement.setSourceType(LeaseSourceType.RENEW);
            } else {
                leaseAgreement.setSourceType(LeaseSourceType.NEW);
            }
            // 设置租约状态为签约待确认
            leaseAgreement.setStatus(LeaseStatus.SIGNING);
            return save(leaseAgreement);
        } else {
            // 更新租约
            return updateById(leaseAgreement);
        }
    }

}




